<template>
    <div class="home_box">
        <bread-crumb></bread-crumb>
        <button>学习 websocket</button>
    </div>
</template>

<script>
import breadCrumb from '../components/breadcrumb.vue'
export default {
    name: 'mainHome',
    components: {
        breadCrumb
    },
    props: {},
    data () {
        return {
            websock: null
        }
    },
    watch: {},
    computed: {},
    methods: {
        initWebScoket () {
            const wsuri = "ws://echo.websocket.org/";
            this.websock = new WebSocket(wsuri);
            this.websock.onmessage = this.websocketonmessage;
            this.websock.onopen = this.websocketonopen;
            this.websock.onerror = this.websocketonerror;
            this.websock.onclose = this.websocketclose;
            // // 初始化一个webSocket 对象
            // let ws = new WebSocket("ws://localhost:8081/home");
            // // 建立连接成功触发事件
            // ws.onopen = function () {
            //     // 使用send()方法发送数据
            //     ws.send("发送数据");
            //     alert('数据发送中...')
            // }
            // // 接受服务端数据时触发事件
            // ws.onmessage = function (evt) {
            //     let received_msg = evt.data;
            //     alert("数据已接收...")
            // }
            // // 断开
            // ws.onclose = function () {
            //     alert('链接已关闭')
            // }
        },
        websocketonopen () {
            //连接建立之后执行send方法发送数据
            let actions = { "test": "12345" };
            this.websocketsend(JSON.stringify(actions));
        },
        websocketonerror () {
            //连接建立失败重连
            this.initWebSocket();
        },
        websocketonmessage (e) { //数据接收
            const redata = JSON.parse(e.data);
            console.log(redata,'redata')
        },
        websocketsend (Data) {//数据发送
            this.websock.send(Data)
        },
        websocketclose (e) {  //关闭
            console.log('断开连接', e)
        }
    },
    destroyed () {
        this.websock.close();
    },
    created () { },
    mounted () {
        this.initWebScoket()
    }
}
</script>
<style lang="less" scoped>
    .home_box {
        width: 100%;
    }
</style>